package com.huanxing.cloud.auth.service;

import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import cn.dev33.satoken.secure.SaSecureUtil;
import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import com.huanxing.cloud.common.core.constant.SecurityConstants;
import com.huanxing.cloud.common.core.enums.DeviceTypeEnum;
import com.huanxing.cloud.common.core.util.ResultOps;
import com.huanxing.cloud.common.myabtis.tenant.HxTenantContextHolder;
import com.huanxing.cloud.common.security.entity.HxUser;
import com.huanxing.cloud.common.security.util.SecurityUtils;
import com.huanxing.cloud.miniapp.api.dto.WxUserLoginReqDTO;
import com.huanxing.cloud.miniapp.api.dto.WxUserReqDTO;
import com.huanxing.cloud.miniapp.api.entity.WxUser;
import com.huanxing.cloud.miniapp.api.feign.RemoteWeiXinUserService;
import com.huanxing.cloud.user.api.dto.UserLoginReqDTO;
import com.huanxing.cloud.user.api.entity.UserInfo;
import com.huanxing.cloud.user.api.feign.RemoteMallUserService;
import com.huanxing.cloud.user.api.vo.UserInfoVO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

@Component
@RequiredArgsConstructor
public class TocLoginService {

	private final RemoteWeiXinUserService remoteWeiXinUserService;

	private final RemoteMallUserService remoteMallUserService;

	public SaTokenInfo maPhoneLogin(UserLoginReqDTO userLoginReqDTO) {
		WxUserLoginReqDTO wxUserLoginReqDTO = new WxUserLoginReqDTO();
		wxUserLoginReqDTO.setAppId(userLoginReqDTO.getAppId());
		wxUserLoginReqDTO.setCode(userLoginReqDTO.getCode());
		// 解密手机号
		WxMaPhoneNumberInfo wxMaPhoneNumberInfo = ResultOps
			.of(remoteWeiXinUserService.getPhoneNumberInfo(wxUserLoginReqDTO, SecurityConstants.SOURCE_IN))
			.getData()
			.orElseThrow(() -> new IllegalArgumentException("login failed"));
		// 通过手机号查询商城用户，不存在创建新用户无需用户注册
		UserInfo userInfo = ResultOps
			.of(remoteMallUserService.getInfoByPhone(wxMaPhoneNumberInfo.getPhoneNumber(),
					userLoginReqDTO.getClientType(), SecurityConstants.SOURCE_IN))
			.getData()
			.orElseThrow(() -> new IllegalArgumentException("login failed"));

		// 获取小程序 openId
		String wxId = userLoginReqDTO.getWxUserId();
		// 查询小程序用户
		WxUser wxUser = ResultOps.of(remoteWeiXinUserService.getInnerById(wxId, SecurityConstants.SOURCE_IN))
			.getData()
			.orElseThrow(() -> new IllegalArgumentException("login failed"));

		// openId绑定商城用户id 用户不退出登录以后都是无感知登录
		WxUserReqDTO wxUserReqDTO = new WxUserReqDTO();
		wxUserReqDTO.setWxUserId(wxId);
		wxUserReqDTO.setUserId(userInfo.getId());
		wxUserReqDTO.setAppId(userLoginReqDTO.getAppId());
		if (!ResultOps.of(remoteWeiXinUserService.bindUserId(wxUserReqDTO, SecurityConstants.SOURCE_IN)).isSuccess()) {
			throw new IllegalArgumentException("login failed");
		}
		HxUser hxUser = new HxUser();
		hxUser.setUserId(userInfo.getId());
		hxUser.setOpenId(wxUser.getOpenid());
		hxUser.setTenantId(userInfo.getTenantId());
		hxUser.setUsername(userInfo.getNickName());
		SecurityUtils.loginByDevice(hxUser, DeviceTypeEnum.TOC);
		return StpUtil.getTokenInfo();
	}

	public SaTokenInfo smsLogin(UserLoginReqDTO userLoginReqDTO) {

		// 通过手机号查询商城用户，不存在创建新用户无需用户注册
		UserInfo userInfo = ResultOps
			.of(remoteMallUserService.getInfoByPhone(userLoginReqDTO.getPhone(), userLoginReqDTO.getClientType(),
					SecurityConstants.SOURCE_IN))
			.getData()
			.orElseThrow(() -> new IllegalArgumentException("login failed"));

		HxUser hxUser = new HxUser();
		if (StringUtils.hasText(userLoginReqDTO.getWxUserId())) {
			// 查询小程序用户
			WxUser wxUser = ResultOps
				.of(remoteWeiXinUserService.getInnerById(userLoginReqDTO.getWxUserId(), SecurityConstants.SOURCE_IN))
				.getData()
				.orElseThrow(() -> new IllegalArgumentException("login failed"));

			// openId绑定商城用户id 用户不退出登录以后都是无感知登录
			WxUserReqDTO wxUserReqDTO = new WxUserReqDTO();
			wxUserReqDTO.setWxUserId(wxUser.getId());
			wxUserReqDTO.setUserId(userInfo.getId());
			wxUserReqDTO.setAppId(userLoginReqDTO.getAppId());
			if (!ResultOps.of(remoteWeiXinUserService.bindUserId(wxUserReqDTO, SecurityConstants.SOURCE_IN))
				.isSuccess()) {
				throw new IllegalArgumentException("login failed");
			}
			hxUser.setOpenId(wxUser.getOpenid());
		}

		hxUser.setUserId(userInfo.getId());
		hxUser.setTenantId(HxTenantContextHolder.getTenantId());
		hxUser.setUsername(userInfo.getNickName());
		SecurityUtils.loginByDevice(hxUser, DeviceTypeEnum.TOC);
		return StpUtil.getTokenInfo();
	}

	public SaTokenInfo passwordLogin(UserLoginReqDTO userLoginReqDTO) {
		// 通过手机号查询商城用户
		UserInfoVO userInfo = ResultOps
			.of(remoteMallUserService.getUserByPhone(userLoginReqDTO.getPhone(), SecurityConstants.SOURCE_IN))
			.getData()
			.orElseThrow(() -> new IllegalArgumentException("请先注册"));

		if (!userInfo.getPassword().equals(SaSecureUtil.md5(userLoginReqDTO.getPassword()))) {
			throw new RuntimeException("账号或密码错误");
		}
		HxUser hxUser = new HxUser();
		hxUser.setUserId(userInfo.getId());
		hxUser.setTenantId(userInfo.getTenantId());
		hxUser.setUsername(userInfo.getNickName());
		SecurityUtils.loginByDevice(hxUser, DeviceTypeEnum.TOC);
		return StpUtil.getTokenInfo();
	}

	public Object maLogin(UserLoginReqDTO userLoginReqDTO) {
		WxUserLoginReqDTO wxUserLoginReqDTO = new WxUserLoginReqDTO();
		wxUserLoginReqDTO.setAppId(userLoginReqDTO.getAppId());
		wxUserLoginReqDTO.setJsCode(userLoginReqDTO.getJsCode());
		WxUser wxUser = ResultOps.of(remoteWeiXinUserService.maLogin(wxUserLoginReqDTO, SecurityConstants.SOURCE_IN))
			.getData()
			.orElseThrow(() -> new IllegalArgumentException("login failed!"));
		if (!StringUtils.hasText(wxUser.getMallUserId())) {
			// 返回微信用户id
			return wxUser.getId();
		}
		// 已绑定商城用户 进行登录
		HxUser hxUser = new HxUser();
		hxUser.setUserId(wxUser.getMallUserId());
		hxUser.setOpenId(wxUser.getOpenid());
		hxUser.setTenantId(wxUser.getTenantId());
		hxUser.setUsername(wxUser.getOpenid());
		SecurityUtils.loginByDevice(hxUser, DeviceTypeEnum.TOC);
		return StpUtil.getTokenInfo();
	}

}
